/**
 * 多模型对比组件
 * 并行调用多个模型进行结果对比
 */

import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Select, 
  Input, 
  Row, 
  Col, 
  Alert, 
  Statistic, 
  Tag, 
  Space,
  Progress,
  Tooltip,
  Typography
} from 'antd';
import { 
  PlayCircleOutlined, 
  ClockCircleOutlined, 
  DollarOutlined, 
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  ThunderboltOutlined
} from '@ant-design/icons';
import { simpleMultiModelService, type SimpleComparisonResult } from '../../services/simple-multi-model.service';

const { Option } = Select;
const { TextArea } = Input;
const { Text, Title } = Typography;

export interface ModelComparisonProps {
  onCompare?: (results: SimpleComparisonResult[]) => void;
  hotItemId?: string;
  platform?: string;
}

export const ModelComparison: React.FC<ModelComparisonProps> = ({ onCompare, hotItemId, platform }) => {
  const [prompt, setPrompt] = useState('');
  const [selectedModels, setSelectedModels] = useState<string[]>([]);
  const [availableModels, setAvailableModels] = useState<string[]>([]);
  const [modelInfos, setModelInfos] = useState<Map<string, any>>(new Map());
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<SimpleComparisonResult[]>([]);
  const [progress, setProgress] = useState(0);
  const [showOfflineModels, setShowOfflineModels] = useState(false);

  // 加载可用模型
  useEffect(() => {
    const loadModels = async () => {
      try {
        console.log('🔄 ModelComparison: 开始加载模型...');
        const models = await simpleMultiModelService.getAvailableModels();
        console.log('📋 ModelComparison: 获取到的模型列表:', models);
        setAvailableModels(models);
        
        // 获取模型详细信息
        const infos = new Map();
        for (const modelId of models) {
          const info = await simpleMultiModelService.getModelInfo(modelId);
          console.log(`📝 ModelComparison: 模型 ${modelId} 信息:`, info);
          if (info) {
            infos.set(modelId, info);
          }
        }
        setModelInfos(infos);
        console.log('🗺️ ModelComparison: 模型信息映射:', infos);
        
        // 默认选择前两个模型
        if (models.length > 0) {
          const defaultSelected = models.slice(0, Math.min(2, models.length));
          console.log('🎯 ModelComparison: 默认选择的模型:', defaultSelected);
          setSelectedModels(defaultSelected);
        }
      } catch (error) {
        console.error('❌ ModelComparison: 加载模型列表失败:', error);
      }
    };
    
    loadModels();
  }, []);

  const handleCompare = async () => {
    if (!prompt.trim() || selectedModels.length === 0) {
      return;
    }

    setLoading(true);
    setProgress(0);
    setResults([]);

    try {
      // 使用真实API调用进行多模型对比
      console.log('开始多模型对比，调用后端API...');
      console.log('选中模型:', selectedModels);
      console.log('提示词:', prompt);

      // 实时进度更新
      let currentProgress = 0;
      const progressInterval = setInterval(() => {
        currentProgress += 5;
        setProgress(Math.min(currentProgress, 90));
      }, 500);

      const comparisonResults = await simpleMultiModelService.compareModels(
        prompt,
        selectedModels,
        2, // 限制并发数，避免过多API调用
        hotItemId,
        platform
      );

      // 完成进度
      clearInterval(progressInterval);
      setProgress(100);
      
      console.log('多模型对比完成:', comparisonResults);
      setResults(comparisonResults);
      onCompare?.(comparisonResults);
      
      setTimeout(() => {
        setProgress(0);
      }, 1000);

    } catch (error) {
      console.error('多模型对比失败:', error);
      // 显示错误信息
      setResults([{
        modelName: 'Error',
        content: '',
        duration: 0,
        error: error instanceof Error ? error.message : '对比失败'
      }]);
    } finally {
      setLoading(false);
    }
  };

  const getResultCard = (result: SimpleComparisonResult) => {
    const hasError = !!result.error;
    const modelInfo = modelInfos.get(result.modelName);
    
    return (
      <Col xs={24} lg={12} key={result.modelName}>
        <Card
          title={
            <Space>
              <div>
                <div>{modelInfo?.name || result.modelName}</div>
                {modelInfo?.provider && (
                  <Tag color="blue" style={{ marginTop: 4, fontSize: '12px' }}>
                    {modelInfo.provider}
                  </Tag>
                )}
              </div>
              {hasError ? (
                <Tag color="error" icon={<ExclamationCircleOutlined />}>失败</Tag>
              ) : (
                <Tag color="success" icon={<CheckCircleOutlined />}>成功</Tag>
              )}
            </Space>
          }
          extra={
            !hasError && (
              <Space>
                <Tooltip title="响应时间">
                  <Text type="secondary">
                    <ClockCircleOutlined /> {result.duration}ms
                  </Text>
                </Tooltip>
                <Tooltip title="估算成本">
                  <Text type="secondary">
                    <DollarOutlined /> ${result.cost}
                  </Text>
                </Tooltip>
              </Space>
            )
          }
          size="small"
          style={{ marginBottom: 16, height: '400px', overflow: 'hidden' }}
        >
          {hasError ? (
            <Alert
              message="生成失败"
              description={result.error}
              type="error"
              showIcon
            />
          ) : (
            <>
              <div style={{ marginBottom: 12 }}>
                <Row gutter={16}>
                  <Col span={8}>
                    <Statistic
                      title="输入Token"
                      value={result.tokenUsage?.prompt || 0}
                      prefix={<ThunderboltOutlined />}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="输出Token"
                      value={result.tokenUsage?.completion || 0}
                      prefix={<ThunderboltOutlined />}
                    />
                  </Col>
                  <Col span={8}>
                    <Statistic
                      title="总Token"
                      value={result.tokenUsage?.total || 0}
                      prefix={<ThunderboltOutlined />}
                    />
                  </Col>
                </Row>
              </div>
              
              <div 
                style={{ 
                  height: '240px', 
                  overflow: 'auto', 
                  padding: '12px', 
                  backgroundColor: '#fafafa',
                  borderRadius: '6px',
                  fontSize: '14px',
                  lineHeight: '1.6',
                  whiteSpace: 'pre-wrap'
                }}
              >
                {result.content}
              </div>
            </>
          )}
        </Card>
      </Col>
    );
  };

  return (
    <div>
      <Card title="多模型对比" style={{ marginBottom: 24 }}>
        <Space direction="vertical" style={{ width: '100%' }} size="large">
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
              <Text strong>选择对比模型：</Text>
              <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                <label style={{ fontSize: '12px', color: '#666', cursor: 'pointer' }}>
                  <input
                    type="checkbox"
                    checked={showOfflineModels}
                    onChange={(e) => setShowOfflineModels(e.target.checked)}
                    style={{ marginRight: 4 }}
                  />
                  显示离线模型
                </label>
                <div style={{ fontSize: '12px', color: '#666' }}>
                  在线模型: {availableModels.length} / 总计: {modelInfos.size}
                </div>
              </div>
            </div>
            <Select
              mode="multiple"
              style={{ width: '100%', marginTop: 8 }}
              placeholder="选择要对比的模型（最多5个）"
              value={selectedModels}
              onChange={setSelectedModels}
              maxTagCount={5}
            >
              {(showOfflineModels ? Array.from(modelInfos.keys()) : availableModels).map(modelId => {
                const modelInfo = modelInfos.get(modelId);
                const isOnline = modelInfo?.status === 'online' || 
                               modelInfo?.status === 'active' || 
                               modelInfo?.status === 'healthy';
                
                return (
                  <Option key={modelId} value={modelId}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <span>{modelInfo?.name || modelId}</span>
                        {modelInfo?.status && (
                          <span style={{ 
                            width: 8, 
                            height: 8, 
                            borderRadius: '50%', 
                            backgroundColor: isOnline ? '#52c41a' : '#ff4d4f',
                            display: 'inline-block'
                          }} />
                        )}
                      </div>
                      <div style={{ display: 'flex', gap: 4 }}>
                        {modelInfo?.provider && (
                          <Tag color="blue" style={{ fontSize: '12px' }}>{modelInfo.provider}</Tag>
                        )}
                        {modelInfo?.status && (
                          <Tag color={isOnline ? 'green' : 'red'} 
                               style={{ fontSize: '12px' }}>
                            {modelInfo.status}
                          </Tag>
                        )}
                      </div>
                    </div>
                  </Option>
                );
              })}
            </Select>
          </div>

          <div>
            <Text strong>输入提示词：</Text>
            <TextArea
              rows={4}
              placeholder="请输入您想要测试的提示词..."
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              style={{ marginTop: 8 }}
            />
          </div>

          <div style={{ textAlign: 'center' }}>
            <Button
              type="primary"
              icon={<PlayCircleOutlined />}
              onClick={handleCompare}
              loading={loading}
              disabled={!prompt.trim() || selectedModels.length === 0}
              size="large"
            >
              开始对比
            </Button>
          </div>

          {loading && (
            <div style={{ textAlign: 'center' }}>
              <Progress 
                percent={Math.round(progress)} 
                status="active"
                format={(percent) => `${percent}% (${Math.round(progress / 100 * selectedModels.length)}/${selectedModels.length})`}
              />
              <Text type="secondary" style={{ display: 'block', marginTop: 8 }}>
                正在并行调用 {selectedModels.length} 个模型...
              </Text>
            </div>
          )}
        </Space>
      </Card>

      {results.length > 0 && (
        <div>
          <Title level={4} style={{ marginBottom: 16 }}>
            对比结果 ({results.length}/{selectedModels.length})
          </Title>
          
          <Row gutter={16}>
            {results.map((result) => getResultCard(result))}
          </Row>

          {results.length === selectedModels.length && (
            <Card title="对比总结" style={{ marginTop: 24 }}>
              {(() => {
                const stats = simpleMultiModelService.getModelStats(results);
                return (
                  <Row gutter={16}>
                    <Col span={6}>
                      <Statistic
                        title="最快响应"
                        value={Math.min(...results.filter(r => !r.error).map(r => r.duration))}
                        suffix="ms"
                        prefix={<ThunderboltOutlined />}
                      />
                      <Text type="secondary" style={{ fontSize: '12px' }}>
                        {stats.fastestModel}
                      </Text>
                    </Col>
                    <Col span={6}>
                      <Statistic
                        title="平均响应时间"
                        value={stats.averageResponseTime}
                        suffix="ms"
                        prefix={<ClockCircleOutlined />}
                      />
                    </Col>
                    <Col span={6}>
                      <Statistic
                        title="成功率"
                        value={stats.successRate}
                        suffix="%"
                        prefix={<CheckCircleOutlined />}
                      />
                    </Col>
                    <Col span={6}>
                      <Statistic
                        title="总成本"
                        value={stats.totalCost}
                        prefix="$"
                      />
                    </Col>
                  </Row>
                );
              })()}
            </Card>
          )}
        </div>
      )}
    </div>
  );
};
